package com.itheima.interceptor;

import com.itheima.Utils.JwtUtils;
import com.itheima.Utils.ThreadLocalUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * 校验Token的拦截器Interceptor
 *
 * @author GY
 * @version V1.0
 * @date 2025-01-16 16:18
 */
@Slf4j
@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("TokenInterceptor preHandle running");
        // 1.获取请求路径
        String uri = request.getRequestURI();
        log.info("uri:{}",uri);
        // 2.校验token
        // 3.从请求头中获取token
        String token = request.getHeader("token");
//        log.info("token:{}",token);
        // 3.1判断token是否为空，如果为空，则返回401，拦截请求
        if (ObjectUtils.isEmpty(token)){
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
        try {
            // 3.2判断token是否有效
            Claims claims = JwtUtils.parseJWT(token);
//            log.info("claims:{}",claims);
            // 3.3有效，放行
            ThreadLocalUtils.set(claims.get("username").toString());
            return true;
        } catch (Exception e) {
            // 3.4 如果无效，则返回401，拦截请求
            e.printStackTrace();
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        ThreadLocalUtils.remove();
    }















    // @Override
    // public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
    //     HttpServletRequest request = (HttpServletRequest) req;
    //     HttpServletResponse response = (HttpServletResponse) res;
    //     String uri = request.getRequestURI();
    //     if (uri.contains("/login")){
    //         chain.doFilter(request,response);
    //         return;
    //     }
    //     String token = request.getHeader("token");
    //     if (ObjectUtils.isEmpty(token)){
    //         response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    //         return;
    //     }
    //     try {
    //         Claims claims = JwtUtils.parseJWT(token);
    //         chain.doFilter(request,response);
    //         return;
    //     }catch (Exception e){
    //         e.printStackTrace();
    //         response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    //         return;
    //     }
    //
    //
    //
    // }

}
